<%inherit file="base.html"/>
<%!
    from utils import translate_time_sec, format_file_size, translate_commit_desc, format_creator
%>

<%def name="main_panel()">
<div id="nav-panel" class="fleft">
    <div class="block">
        <h3>${_("Navigation")}</h3>
        <ul>
            <li><a href="/" id="back">${_("All Libraries")}</a></li>
            % if relay and relay.props.service_url:
            <li><a href="${relay.props.service_url}/repo/${repo.props.id}">${_("View on Website")}</a></li>
            % endif
        </ul>
        <h3>${_("Operations")}</h3>
        <ul class="repo-ops">
            <li><span class="icon-repeat"></span><a id="do-sync-link" href="/repos/operation/?repo=${repo.props.id}&op=sync">${_("Sync Now")}</a></li>
            <li><span class="icon-unlink"></span><a href="#" id="delete">${_("Unsync")}</a></li>
            <li><span class="icon-pencil"></span><a href="#" id="edit-relay">${_("Edit Server Address")}</a></li>
        </ul>
    </div>
</div> <!-- nav-panel -->

<div id="con-panel" class="fright">
    <div class="block">
        <div id="transfer-area"></div><!-- transfer area -->

        <h2 id="repo-name">
            ${repo.props.name}
            % if repo.props.encrypted:
            <span class="encrypt-note">[${_("Encrypted")}]</span>
            % endif
            <span class="sync-note"></span>
        </h2>

        <div class="basic-info">
            <p class="repo-desc">${repo.props.desc}</p>
            % if not repo.props.worktree_invalid:
            <span class="item-name">${_("Local Path:")}</span> <a href="/repos/operation/?repo=${repo.props.id}&op=open">${repo.props.worktree}</a>
            % endif

            <h3>${_("Sync Info")}</h3>
            <ul>
                % if relay and relay.name:
                <li>
                <span class="item-name">${_("Server: ")}</span>${relay.name}
                </li>
                % endif

                <li>
                % if repo.props.auto_sync:
                <span class="item-name">${_("Auto Sync: ")}</span><input type="checkbox" checked="checked" data="set-manual-sync" id="set-sync-btn" />
                % else:
                <span class="item-name">${_("Auto Sync: ")}</span><input type="checkbox" data="set-auto-sync" id="set-sync-btn" />
                % endif
                <span id="sync-set-feedback" class="notification hide"></span>
                </li>
            </ul>
        </div>

        <!-- hidden content -->
        <textarea id="transfer-template" class="hide"> 
            <div class="notification">
                {#if $T.state == "normal"}
                {#if $T.ttype == "upload"}${_("uploading")}{#else}${_("downloading")}{#/if}
                {#if $T.block_done > 0}
                <span id="transfered">, ${_("transfered")} {parseInt($T.block_done * 100 / $T.block_total)}%</span>
		{#else}
		<span id="transfered">, ${_("transfered")} 0%</span>
                {#/if}
                {#if $T.rate >= 0}
                , ${_("rate")} <span id="tranfer-rate">{parseInt($T.rate/1024)}</span> KB/${_("s")}
                {#/if}
                <img src="/static/img/icon_loading.gif" width="16" height="16" />
                {#/if}

                {#if $T.state == "error"}
                ${_("Library transfer error:")} {$T.error_str}.<br/>
                {#/if}
            </div>
        </textarea>

        <div id="unsync-confirm" class="hide">
            <p><span class="ui-icon ui-icon-alert vam"></span><span class="vam">${_("Really want to unsync this library?")}</span></p>
            <button id="remove-repo-btn" data="/repos/operation/?repo=${repo.props.id}&op=remove">${_("Unsync")}</button>
            <button class="simplemodal-close">${_("Cancel")}</button>
        </div>

        <form id="edit-relay-form" method="POST" action="/repos/operation/?repo=${repo.props.id}&op=edit-relay" class="hide">
            <h2>${_("Edit Server address")}</h2>
            <p class="warning">
                <strong>${_("Warning:")}</strong> ${_("You should only edit the server address when you're sure the server has used a new address. Otherwise it may make the libraries unable to be synchronized. After edit the address, you should restart seafile for the changes to take effect.")}
            </p>
            % if relay and relay.name:
            <div class="form-row">
                <label for="relay_name">${_("server name")}:</label>
                <span>${relay.name}</span>
            </div>
            % endif
            <div class="form-row">
                <label for="relay_addr">${_("server address")}:</label>
                <input type="text" name="relay_addr" value="${relay_addr}" maxlength="40" />
            </div>
            <div class="form-row">
                <label for="relay_port">${_("server port")}:</label>
                <input type="text" name="relay_port" value="${relay_port}" maxlength="5" />
            </div>
            <p id="edit-relay-error" class="error"></p>
            <input type="submit" id="edit-relay-submit" value="${_("Submit")}" />
        </form>
    </div>
</div>
</%def>

<%def name="js()">
<script type="text/javascript">
$("#open-dir-btn, #remove-repo-btn").click(function() {
    location.href = $(this).attr('data');
});

//delete dialog
$("#delete").click(function() {
    $("#unsync-confirm").modal({appendTo: "#main", focus:false}); 
    return false;
});

$('#edit-relay').click(function() {
    $("#edit-relay-form").modal({appendTo: "#main"}); 
    return false;
});

$('#edit-relay-form').submit(function() {
    var addr = $('input[name="relay_addr"]').val();
    var port = $('input[name="relay_port"]').val();
    var addr_re = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
    var port_re = /^[\d]+$/;

    var show_error = function(msg) {
        $('#edit-relay-error').html(msg);
        $("#simplemodal-container").css({'height':'auto'});
    };

    if (!addr) {
        show_error('${_("server address can not be empty")}');
        return false;
    } else if (!addr_re.test(addr)) {
        show_error('${_("server address is invalid")}');
        return false;
    }
                             
    if (!port) {
        show_error('${_("server port can not be empty")}');
        return false;
    } else if (!port_re.test(port)) {
        show_error('${_("server port is invalid")}');
        return false;
    } else {
        port = Number(port);
        if (isNaN(port) || port < 0 || port > 65535) {
            show_error('${_("server port is invalid")}');
            return false;
        }
    }

    return true;
});

// revert dialog
var revert_commit = "";
$("a.revert-link").bind('click', function() {
    revert_commit = $(this).attr("data");
    $("#dialog-revert-confirm").modal({appendTo: "#main"}); 
});
$("#revert-repo-btn").click(function() {
    location.href = "/repos/operation/?repo=${repo.props.id}&op=revert&commit=" + revert_commit;
});

% if relay and repo.local_branch and repo.props.head_branch and not repo.props.worktree_invalid:
var empty_count = 0;
var has_transfer = false;
var last_sync_status = '';

function set_sync_status(status) {
    if (status == last_sync_status) {
        return false;
    }
    last_sync_status = status;
    var str = '';
    switch (status) {
        case 'synchronized':
            str = "${_('synchronized')}";
            break;
        case 'committing':
            str = "${_('indexing files')}";
            break;
        case 'initializing': 
            str = "${_('sync initializing')}";
            break;
        case 'downloading': 
            str = "${_('downloading')}";
            break;
        case 'uploading': 
            str = "${_('uploading')}";
            break;
        case 'merging': 
            str = "${_('sync merging')}";
            break;
        case 'waiting for sync':
            str = "${_('waiting for sync')}";
            break;
        case 'relay not connected':
            str = "${_('server not connected')}";
            break;
        case 'relay authenticating':
            str = "${_('server authenticating')}";
            break;
        case 'auto sync is turned off':
            str = "${_('auto sync is turned off')}";
        default: 
            str = status;
    }
    $(".sync-note").html('(${_("sync status:")} ' + str + ')');
}

function set_sync_error(error) {
    if (error == last_sync_status) {
        return false;
    }
    last_sync_status = error;
    var str = '';
    switch (error) {
        case "relay not connected":
            str = "${_('server not connected')}";
            break;
        case "Server has been removed":
            str = "${_('Server has been removed')}";
            break;
        case "You have not login to the server":
            str = "${_('You have not login to the server')}";
            str = str + ' ${relay.name}. ' + '${_("Go to")} ' + '<a href="/peers/">${_("Network")}</a>' + ' ${_("page to login")}';
            break;
        case "You do not have permission to access this repo":
            str = "${_('You do not have permission to access this library')}";
            break;
        case "The storage space of the repo owner has been used up":
            str = "${_('The storage space of the library owner has been used up')}";
            break;
        case "Remote service is not available":
            str = "${_('Remote service is not available')}";
            break;
        case "Access denied to service. Please check your registration on relay.":
            str = "${_('Access denied to service. Please login to the server on \'Network\' page.')}";
            break;
        case "Internal data corrupted.":
            str = "${_('Internal data corrupted.')}";
            break;
        case "Failed to start upload.":
            str = "${_('Failed to start upload.')}";
            break;
        case "Error occured in upload.":
            str = "${_('Error occured in upload.')}";
            break;
        case "Failed to start download.":
            str = "${_('Failed to start download.')}";
            break;
        case "Error occured in download.":
            str = "${_('Error occured in download.')}";
            break;
        case "No such repo on relay.":
            str = "${_('Library is deleted on server. Click \'Unsync\' button, then you can create a new library.')}";
            break;
        case "Unknown error.":
            str = "${_('Unknown error.')}";
            break;
        default:
            str = error;
    }    
    $(".sync-note").html('(${_("sync error:")} ' + '<span class="error">' + str + '</span>)');
}

function show_sync_status() {
    $.ajax({
        url: '/repo/sync-status/?repo=${repo.props.id}', 
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            if (data["state"]) {
                if (data["state"] == "error") {
                    set_sync_error(data["error"]);
                } else {
                    set_sync_status(data["state"]);
                    if (data["state"] == "uploading" || data["state"] == "downloading") {
                        show_repo_transfer();
                        has_transfer = true;
                    } else {
                        if (has_transfer) {
                            $("#transfer-area").empty();
                            location.reload();
                            has_transfer = false;
                        }
                    }
                }
            }
            if (data['state'] == 'synchronized') {
                empty_count++;
            }
            if (empty_count < 4) {
                setTimeout(show_sync_status, 2000);
            }
        }
    });
}

function show_repo_transfer() {
    $.ajax({
        url: '/repo/transfer/?repo=${repo.props.id}',
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            if (data["ttype"]) {
                $("#transfer-area").setTemplateElement("transfer-template");
                $("#transfer-area").processTemplate(data);
            } else {
                $("#transfer-area").empty();
            }
        }
    });
}

show_sync_status();

$('#do-sync-link').click(function() {
    set_sync_status('initializing');
});
% endif

//for auto-sync setting
$("#set-sync-btn").click(function() { 
    $.ajax({
        url: '/repos/operation/?repo=${repo.props.id}&op=' + $(this).attr('data'),
        dataType: 'json',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data) {
            if (data['start']) {
                $('#set-sync-btn').attr('data','set-manual-sync');
                $('#sync-set-feedback').html('${_("Started")}');
            } else {
                $('#set-sync-btn').attr('data','set-auto-sync');
                $('#sync-set-feedback').html('${_("Stopped")}');
            }
            $('#sync-set-feedback').removeClass('hide');
            setTimeout(function() { $('#sync-set-feedback').addClass('hide'); }, 1500);
        }
    }); 
});
</script>
</%def>
